package com.exception;

import com.dto.DTO;
import com.dto.MessageEnum;
import com.utils.ExceptionUtils;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.dao.RecoverableDataAccessException;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.ConnectException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;

//import org.apache.shiro.authz.UnauthorizedException;

//import org.apache.shiro.authz.UnauthorizedException;

//spring会在容器中找 那个bean实现了HandlerExceptionResolver 异常解析器  把所有的异常都交给他处理
//处理就是将认识的异常的信息 转换成对应中文的 自定义异常 再处理
@ControllerAdvice
public class CustomExceptionResolver{

	//spring 获取到异常就会 调用 下面的resolveException 来处理异常

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public  DTO resolveExceptionProcess(HttpServletRequest request, HttpServletResponse response, Object obj,
                                           Exception ex) {
		ex.printStackTrace();
		DTO dto = new DTO();
		System.out.println("-----------有异常处理-------------");
		Exception e = ExceptionUtils.changeToCustomException(ex);
		System.out.println(e.getMessage());//服务器查看一下异常信息，后面换成日志输出
		if(e instanceof  RedirectException){//如果是跳转异常就需要切割信息 1为 提示信息 2为跳转
			String[] split = e.getMessage().split(";");
			dto.setCode(302);
             dto.setMsg(split[0]);
             dto.setUrl(split[1]);
		}else{
			dto.setCode(409);
			dto.setMsg(e.getMessage());
		}

		return dto;

	}



}